#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LEN 1024

int read_line(char *buffer, int max_len, FILE *fp)
{
    char temp;
    int i;
    int ret;
    for (i = 0; i < max_len; i++)
    {
        if ((ret = fread(&temp, 1, 1, fp)) < 0)
        {
            perror("read data error!");
            return -1;
        }

        if (ret == 0)
        {
            buffer[i] = '\0';
            return 0;
        }

        if (temp == '\n')
        {
            buffer[i] = temp;
            break;
        }

        buffer[i] = temp;
    }

    buffer[i + 1] = '\0';

    return i + 1;
}

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        printf("Please input filename\n");
        exit(1);
    }

    FILE *fp = NULL;
    FILE *fp2 = NULL;
    char buffer[MAX_LEN];

    if ((fp = fopen(argv[1], "r")) == NULL)
    {
        perror("open file error!");
        exit(1);
    }

    if ((fp2 = fopen(argv[2], "w+")) == NULL)
    {
        perror("open file error!");
        exit(1);
    }

    fgetc(fp);

    if (feof(fp))
    {
        printf("file is empty!\n");
        exit(1);
    }
    else
    {
        rewind(fp);
    }
#if 0
    for (int i = 0; i < 3; i++)
    {
        memset(buffer, 0, sizeof(buffer));
        gets(buffer);
        if (fwrite(buffer, 1, strlen(buffer), fp) < 0)
        {
            perror("write data error!");
            exit(1);
        }

        fwrite("\n", 1, 1, fp);
    }
#endif

#if 0
    //rewind(fp);
    memset(buffer, 0, sizeof(buffer));

    // while(read_line(buffer, MAX_LEN, fp) != 0)
    // {
    //     printf("%s", buffer);
    //     memset(buffer, 0, sizeof(buffer));
    // }

    while (!feof(fp))
    {
        memset(buffer, 0, sizeof(buffer));
        read_line(buffer, MAX_LEN, fp);
        printf("%s", buffer);
    }
#endif
#if 0
    while(!feof(fp))
    {
        memset(buffer, 0, sizeof(buffer));
        //fread(buffer, 1, sizeof(buffer) - 1, fp);
        if(read_line(buffer, MAX_LEN, fp) < 0)
        {
            perror("read data error!");
            exit(1);
        }

        fwrite(buffer, 1, strlen(buffer), fp2);
    }
#endif
#if 0
//fgetc  fputc  getc() putc()
    char temp;
    while((temp = fgetc(fp)) != EOF)
    {
        //printf("%c", temp);
        //putchar(temp);
        putc(temp, fp2);
    }

    fclose(fp);
#endif
    memset(buffer, 0, sizeof(buffer));
    while(fgets(buffer, MAX_LEN, fp) != NULL)
    {
        fputs(buffer, fp2);
        memset(buffer, 0, sizeof(buffer));
    }
    return 0;
}